package com.chatsimple.netty

import com.chatsimple.Const
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelOption
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import java.io.Closeable

class NettyServer : Closeable {
    private lateinit var serverBootstrap: ServerBootstrap

    fun start() {
        val bossGroup = NioEventLoopGroup() //处理连接group
        val workerGroup = NioEventLoopGroup()//处理数据group
        serverBootstrap = ServerBootstrap().group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel::class.java)
            .childHandler(ServerChannelInitializer())
            .option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
        serverBootstrap.bind(Const.PORT).sync().channel().closeFuture().sync()
    }

    override fun close() {
        if (this::serverBootstrap.isInitialized) {
            serverBootstrap.config().group().shutdownGracefully()
        }
    }
}